package cn.bonoon.kernel.util;

import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

public final class RequestHelper {

	private RequestHelper() { }

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (!isIp(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (!isIp(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (!isIp(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static boolean isIp(String ip){
		return null != ip && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip);
	}
	
	public static String getAgent(HttpServletRequest request){
		String agent = request.getHeader("user-agent");
		return agent;
	}
	
	public static boolean isAjax(HttpServletRequest request){
		return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("x-requested-with"));
	}
	
	public static BrowserInfo getBrowserInfo(HttpServletRequest request){
		String agent = request.getHeader("user-agent");
		StringTokenizer st = new StringTokenizer(agent,";");

		BrowserInfo info = new BrowserInfo();
		info.browserType = st.nextToken();

		//得到用户的浏览器名

		info.browserName = st.nextToken();

		//得到用户的操作系统名

		info.systemName = st.nextToken();
		
		return info;
	}
	
	public static class BrowserInfo{
		private String browserType;
		private String browserName;
		private String systemName;
		public String getBrowserType() {
			return browserType;
		}
		public void setBrowserType(String browserType) {
			this.browserType = browserType;
		}
		public String getBrowserName() {
			return browserName;
		}
		public void setBrowserName(String browserName) {
			this.browserName = browserName;
		}
		public String getSystemName() {
			return systemName;
		}
		public void setSystemName(String systemName) {
			this.systemName = systemName;
		}
	}
}
